
package com.hlkj.pay.app.merchant.ext.impl.helipay.handler;
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

import com.hlkj.framework.common.pojo.CommonResult;
import com.hlkj.framework.common.util.id.IdUtils;
import com.hlkj.framework.common.util.json.JsonUtils;
import com.hlkj.framework.http.template.OkHttpTemplate;
import com.hlkj.pay.app.merchant.ext.dto.access.ChannelMerchantAccessContext;
import com.hlkj.pay.app.merchant.ext.dto.access.ChannelMerchantAccessQueryContext;
import com.hlkj.pay.app.merchant.ext.dto.access.ChannelMerchantAccessSignContext;
import com.hlkj.pay.app.merchant.ext.dto.access.ChannelMerchantBusinessContext;
import com.hlkj.pay.app.merchant.ext.impl.helipay.dto.HeliPayAccessExtentDto;
import com.hlkj.pay.app.merchant.ext.impl.helipay.dto.HeliPayConfig;
import com.hlkj.pay.app.merchant.ext.impl.helipay.dto.req.HeliPayAccessAuthQueryRes;
import com.hlkj.pay.app.merchant.ext.impl.helipay.dto.req.HeliPayAccessQueryRes;
import com.hlkj.pay.app.merchant.ext.impl.helipay.dto.req.HeliPayAccessSubimtRes;
import com.hlkj.pay.app.merchant.ext.impl.helipay.dto.req.HeliPayAccessUpdateRes;
import com.hlkj.pay.controller.common.ConfigController;
import com.hlkj.pay.dto.merchant.MerchantAccessDto;
import com.hlkj.pay.dto.merchant.MerchantAccessSignLink;
import com.hlkj.pay.dto.merchant.ProviderChannelFeeConfigList;
import com.hlkj.pay.enums.CommonEnum;
import com.hlkj.pay.enums.MerchantEnum;
import com.hlkj.pay.enums.PayEnums;
import com.hlkj.pay.infrastructure.model.merchant.*;
import com.hlkj.pay.infrastructure.model.pay.PayChannelRequestDO;
import com.hlkj.pay.infrastructure.model.pay.PayWayDO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @author HlpayTeam
 * @date 2024/10/16 9:10
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class HeliPayMerchantAccessInfoHandler extends HeliPayMerchantCommonParamsHandle {

    private final HeliPayMerchantParamsHandle heliPayMerchantParamsHandle;

    private final OkHttpTemplate okHttpTemplate;

    private final ConfigController configController;

    /**
     *
     * @param channelMerchantAccessContext
     */
    public void merchantAccess(ChannelMerchantAccessContext channelMerchantAccessContext) {
        CommonResult<HeliPayConfig> heliPayConfigCommonResult = heliPayMerchantParamsHandle.heliPayConfig(channelMerchantAccessContext.getProviderChannelConfig(),
                channelMerchantAccessContext.isTest());
        if (!heliPayConfigCommonResult.isSuccess()) {
            channelMerchantAccessContext.setProcessStatus(false);
            channelMerchantAccessContext.setRemark(heliPayConfigCommonResult.getMsg());
            return;
        }
        HeliPayConfig heliPayConfig = heliPayConfigCommonResult.getData();
        CommonResult<Void> paramsCheckResult = heliPayMerchantParamsHandle.merchantApplyParamsCheck(channelMerchantAccessContext);
        if (!paramsCheckResult.isSuccess()) {
            channelMerchantAccessContext.setProcessStatus(false);
            channelMerchantAccessContext.setRemark(paramsCheckResult.getMsg());
            return;
        }
        try {
            Map<String, Object> params;

            MerchantAccessInfoDO merchantAccessInfo = channelMerchantAccessContext.getMerchantAccessDto().getMerchantAccessInfo();
            String accessUrl = heliPayMerchantParamsHandle.accessUrl(channelMerchantAccessContext.isTest());
            PayChannelRequestDO payChannelRequestDO = new PayChannelRequestDO();
            payChannelRequestDO.setRequestUrl(accessUrl);
            channelMerchantAccessContext.setPayChannelRequestDO(payChannelRequestDO);
            // 信息更新
            if (StringUtils.hasText(merchantAccessInfo.getSubMchId())) {
                params = heliPayMerchantParamsHandle.updateMerchantApplyParams(channelMerchantAccessContext);
                String orderNo = IdUtils.getSnowflakeNextIdStr();
                params.put("orderNo", orderNo);
                String requestBody = JsonUtils.toJsonString(params);
                payChannelRequestDO.setRequestParams(requestBody);
                CommonResult<HeliPayAccessUpdateRes> commonResult = heliPayAccessRequest(accessUrl, "infoAlteration", heliPayConfig, requestBody, HeliPayAccessUpdateRes.class);
                log.info("合利宝 进件更新 返回参数 :{}", JsonUtils.toJsonString(commonResult));
                payChannelRequestDO.setRequestParams(JsonUtils.toJsonString(commonResult.getData()));
                HeliPayAccessUpdateRes data = commonResult.getData();
                if (!commonResult.isSuccess()) {
                    channelMerchantAccessContext.setProcessStatus(false);
                    channelMerchantAccessContext.setRemark(commonResult.getMsg());
                    return;
                }
                params = new HashMap<>();
                params.put("orderNo", orderNo);
                params.put("merchantNo", merchantAccessInfo.getSubMchId());
                params.put("merchantEntryAlterationType", "MERCHANT_INFO");
                commonResult = heliPayAccessRequest(accessUrl, "queryAlteration", heliPayConfig, JsonUtils.toJsonString(params), HeliPayAccessUpdateRes.class);
                Thread.sleep(10000);
                if (!commonResult.isSuccess()) {
                    channelMerchantAccessContext.setProcessStatus(false);
                    channelMerchantAccessContext.setRemark(commonResult.getMsg());
                    return;
                }
                if ("REFUSE".equals(data.getAlterationStatus())) {
                    channelMerchantAccessContext.setProcessStatus(false);
                    channelMerchantAccessContext.setRemark(data.getResult());
                }
                else if ("AUDITED".equals(data.getAlterationStatus())) {
                    // 上一个状态
                    MerchantEnum.ACCESS_STATUS accessStatus = MerchantEnum.ACCESS_STATUS.from(merchantAccessInfo.getLastStatus());
                    channelMerchantAccessContext.setAccessStatus(accessStatus);
                    // 需要同步上传文件
                    try{
                        fileProcess(accessUrl, channelMerchantAccessContext, heliPayConfig);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                else {
                    // 审核通过进入资料上传
                    channelMerchantAccessContext.setAuditStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.SIGN);
                    channelMerchantAccessContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.CHANNEL_APPROVE);
                    // 需要同步上传文件
                    try{
                        fileProcess(accessUrl, channelMerchantAccessContext, heliPayConfig);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
            else {
                // 新增信息
                params = heliPayMerchantParamsHandle.merchantApplyParams(channelMerchantAccessContext, heliPayConfig);
                String requestBody = JsonUtils.toJsonString(params);
                payChannelRequestDO.setRequestParams(requestBody);
                CommonResult<HeliPayAccessSubimtRes> commonResult = heliPayAccessRequest(accessUrl, "register", heliPayConfig, requestBody, HeliPayAccessSubimtRes.class);
                log.info("合利宝 新增进件 返回参数 :{}", JsonUtils.toJsonString(commonResult));
                HeliPayAccessSubimtRes data = commonResult.getData();
                payChannelRequestDO.setRequestParams(JsonUtils.toJsonString(commonResult.getData()));
                if (!commonResult.isSuccess()) {
                    channelMerchantAccessContext.setProcessStatus(false);
                    channelMerchantAccessContext.setRemark(commonResult.getMsg());
                    return;
                }

                if ("OVERRULE".equals(data.getEntryStatus())) {
                    channelMerchantAccessContext.setProcessStatus(false);
                    channelMerchantAccessContext.setRemark(data.getMsg());
                }
                else if ("AUDITED".equals(data.getEntryStatus())) {
                    merchantAccessInfo.setApplyNo(data.getOrderNo());
                    payChannelRequestDO.setApplyNo(data.getOrderNo());
                    merchantAccessInfo.setSubMchId(data.getMerchantNo());
                    HeliPayAccessExtentDto heliPayAccessExtentDto = new HeliPayAccessExtentDto();
                    heliPayAccessExtentDto.setSysAccountNo(data.getSysAccountNo());
                    merchantAccessInfo.setExtendA(JsonUtils.toJsonString(heliPayAccessExtentDto));
                    // 审核通过进入资料上传
                    channelMerchantAccessContext.setAuditStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.SIGN);
                    channelMerchantAccessContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.CHANNEL_APPROVE);
                    // 需要同步上传文件
                    try{
                        fileProcess(accessUrl, channelMerchantAccessContext, heliPayConfig);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                else {
                    merchantAccessInfo.setApplyNo(data.getOrderNo());
                    payChannelRequestDO.setApplyNo(data.getOrderNo());
                    if (StringUtils.hasText(data.getMerchantNo())) {
                        merchantAccessInfo.setSubMchId(data.getMerchantNo());
                    }
                    merchantAccessInfo.setRemark(data.getMsg());
//                    channelMerchantAccessContext.setRemark(data.getMsg());
                    // 待审核进入资料上传
                    channelMerchantAccessContext.setAuditStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.SIGN);
                    channelMerchantAccessContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.CHANNEL_APPROVE);
                    // 需要同步上传文件
                    try{
                        fileProcess(accessUrl, channelMerchantAccessContext, heliPayConfig);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            channelMerchantAccessContext.setProcessStatus(false);
            channelMerchantAccessContext.setRemark(e.getMessage());
        }
    }

    public void fileProcess(String accessUrl, ChannelMerchantAccessContext channelMerchantAccessContext,HeliPayConfig heliPayConfig) {
        MerchantAccessDto merchantAccessDto = channelMerchantAccessContext.getMerchantAccessDto();
        MerchantAccessInfoDO merchantAccessInfo = merchantAccessDto.getMerchantAccessInfo();
        MerchantAccessLicenseDO merchantAccessLicense = merchantAccessDto.getMerchantAccessLicense();
        MerchantAccessCertInfoDO merchantAccessCert = merchantAccessDto.getMerchantAccessLegal();
        MerchantAccessCardDO merchantAccessCard = merchantAccessDto.getMerchantAccessCard();
        MerchantAccessBusinessDO merchantAccessBusiness = merchantAccessDto.getMerchantAccessBusiness();

        upload(heliPayConfig, accessUrl, merchantAccessInfo, merchantAccessLicense.getLicenseUrl(), "BUSINESS_LICENSE");
        upload(heliPayConfig, accessUrl, merchantAccessInfo, merchantAccessCert.getCertFrontUrl(), "FRONT_OF_ID_CARD");
        upload(heliPayConfig, accessUrl, merchantAccessInfo, merchantAccessCert.getCertBackUrl(), "BACK_OF_ID_CARD");
        upload(heliPayConfig, accessUrl, merchantAccessInfo, merchantAccessCard.getLicenseUrl(), "PERMIT_FOR_BANK_ACCOUNT");
        upload(heliPayConfig, accessUrl, merchantAccessInfo, merchantAccessCard.getSettleCardFrontUrl(), "BANK_CARD");
        upload(heliPayConfig, accessUrl, merchantAccessInfo, merchantAccessCard.getCertFrontUrl(), "SETTLE_FRONT_OF_ID_CARD");
        upload(heliPayConfig, accessUrl, merchantAccessInfo, merchantAccessCard.getCertBackUrl(), "SETTLE_BACK_OF_ID_CARD");
        upload(heliPayConfig, accessUrl, merchantAccessInfo, merchantAccessCard.getAuthUrl(), "AUTHORIZATION_FOR_SETTLEMENT");
        upload(heliPayConfig, accessUrl, merchantAccessInfo, merchantAccessBusiness.getStoreHeaderUrl(), "SIGN_BOARD");
        upload(heliPayConfig, accessUrl, merchantAccessInfo, merchantAccessBusiness.getStoreIndoorUrl(), "INTERIOR_PHOTO");

        if (!CollectionUtils.isEmpty(merchantAccessBusiness.getFileUrls())) {
            upload(heliPayConfig, accessUrl, merchantAccessInfo, merchantAccessBusiness.getFileUrls().get(0), "HANDHELD_OF_BANK_CARD");
        }

        upload(heliPayConfig, accessUrl, merchantAccessInfo, merchantAccessCard.getSettleCertFrontUrl(), "HANDHELD_OF_ID_CARD");
    }

    public void fileProcess(ChannelMerchantBusinessContext channelMerchantBusinessContext) {
        CommonResult<HeliPayConfig> heliPayConfigCommonResult = heliPayMerchantParamsHandle.heliPayConfig(channelMerchantBusinessContext.getProviderChannelConfig(),
                channelMerchantBusinessContext.isTest());
        if (!heliPayConfigCommonResult.isSuccess()) {
            channelMerchantBusinessContext.setProcessStatus(false);
            channelMerchantBusinessContext.setRemark(heliPayConfigCommonResult.getMsg());
            return;
        }
        String accessUrl = heliPayMerchantParamsHandle.accessUrl(channelMerchantBusinessContext.isTest());
        HeliPayConfig heliPayConfig = heliPayConfigCommonResult.getData();
        MerchantAccessDto merchantAccessDto = channelMerchantBusinessContext.getMerchantAccessDto();
        MerchantAccessInfoDO merchantAccessInfo = merchantAccessDto.getMerchantAccessInfo();
        MerchantAccessLicenseDO merchantAccessLicense = merchantAccessDto.getMerchantAccessLicense();
        MerchantAccessCertInfoDO merchantAccessCert = merchantAccessDto.getMerchantAccessLegal();
        MerchantAccessCardDO merchantAccessCard = merchantAccessDto.getMerchantAccessCard();
        MerchantAccessBusinessDO merchantAccessBusiness = merchantAccessDto.getMerchantAccessBusiness();

        upload(heliPayConfig, accessUrl, merchantAccessInfo, merchantAccessLicense.getLicenseUrl(), "BUSINESS_LICENSE");
        upload(heliPayConfig, accessUrl, merchantAccessInfo, merchantAccessCert.getCertFrontUrl(), "FRONT_OF_ID_CARD");
        upload(heliPayConfig, accessUrl, merchantAccessInfo, merchantAccessCert.getCertBackUrl(), "BACK_OF_ID_CARD");
        upload(heliPayConfig, accessUrl, merchantAccessInfo, merchantAccessCard.getLicenseUrl(), "PERMIT_FOR_BANK_ACCOUNT");
        upload(heliPayConfig, accessUrl, merchantAccessInfo, merchantAccessCard.getSettleCardFrontUrl(), "BANK_CARD");
        upload(heliPayConfig, accessUrl, merchantAccessInfo, merchantAccessCard.getCertFrontUrl(), "SETTLE_FRONT_OF_ID_CARD");
        upload(heliPayConfig, accessUrl, merchantAccessInfo, merchantAccessCard.getCertBackUrl(), "SETTLE_BACK_OF_ID_CARD");
        upload(heliPayConfig, accessUrl, merchantAccessInfo, merchantAccessCard.getAuthUrl(), "AUTHORIZATION_FOR_SETTLEMENT");
        upload(heliPayConfig, accessUrl, merchantAccessInfo, merchantAccessBusiness.getStoreHeaderUrl(), "SIGN_BOARD");
        upload(heliPayConfig, accessUrl, merchantAccessInfo, merchantAccessBusiness.getStoreIndoorUrl(), "INTERIOR_PHOTO");

        if (!CollectionUtils.isEmpty(merchantAccessBusiness.getFileUrls())) {
            upload(heliPayConfig, accessUrl, merchantAccessInfo, merchantAccessBusiness.getFileUrls().get(0), "HANDHELD_OF_BANK_CARD");
        }

        upload(heliPayConfig, accessUrl, merchantAccessInfo, merchantAccessCard.getSettleCertFrontUrl(), "HANDHELD_OF_ID_CARD");
        // 审核通过进入资料上传
        channelMerchantBusinessContext.setAuditStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.AUDITING);
    }

    public void upload(HeliPayConfig heliPayConfig, String accessUrl, MerchantAccessInfoDO merchantAccessInfo, String url, String type) {
        if (StringUtils.isEmpty(url)) {
            return;
        }
        Map<String, Object> params = new HashMap<>();
        if (StringUtils.hasText(merchantAccessInfo.getSubMchId())) {
            params.put("merchantNo", merchantAccessInfo.getSubMchId());
        } else {
            params.put("orderNo", merchantAccessInfo.getApplyNo());
        }
        params.put("credentialType", type);
        params.put("credentialUrl", url);
        String paramsString = JsonUtils.toJsonString(params);
        CommonResult<Map> commonResult = heliPayAccessRequest(accessUrl, "uploadImageUrl", heliPayConfig, paramsString, Map.class);
        log.info("合利宝 文件上传 返回参数 :{}", JsonUtils.toJsonString(commonResult));
    }

    /**
     * 进件查询
     *
     * @param channelMerchantAccessQueryContext
     */
    public void accessQueryRequest(ChannelMerchantAccessQueryContext channelMerchantAccessQueryContext) {
        CommonResult<HeliPayConfig> heliPayConfigCommonResult = heliPayMerchantParamsHandle.heliPayConfig(channelMerchantAccessQueryContext.getProviderChannelConfig(),
                channelMerchantAccessQueryContext.isTest());
        if (!heliPayConfigCommonResult.isSuccess()) {
            channelMerchantAccessQueryContext.setProcessStatus(false);
            channelMerchantAccessQueryContext.setRemark(heliPayConfigCommonResult.getMsg());
            return;
        }
        MerchantAccessInfoDO merchantAccessInfo = channelMerchantAccessQueryContext.getMerchantAccessInfo();
        HeliPayConfig heliPayConfig = heliPayConfigCommonResult.getData();
        Map<String, Object> params = new HashMap<>();
        params.put("orderNo", merchantAccessInfo.getRequestId());
        params.put("firstClassMerchantNo", heliPayConfig.getMerchantNo());
        String paramsString = JsonUtils.toJsonString(params);
        String accessUrl = heliPayMerchantParamsHandle.accessUrl(channelMerchantAccessQueryContext.isTest());
        try {
            CommonResult<HeliPayAccessQueryRes> commonResult = heliPayAccessRequest(accessUrl, "registerQuery", heliPayConfig, paramsString, HeliPayAccessQueryRes.class);
            log.info("合利宝 进件查询 返回参数 :{}", JsonUtils.toJsonString(commonResult));
            if (!commonResult.isSuccess()) {
                channelMerchantAccessQueryContext.setProcessStatus(false);
                channelMerchantAccessQueryContext.setRemark(commonResult.getMsg());
                return;
            }
            if (!commonResult.isSuccess()) {
                channelMerchantAccessQueryContext.setProcessStatus(false);
                channelMerchantAccessQueryContext.setRemark(commonResult.getMsg());
                return;
            }
            HeliPayAccessQueryRes data = commonResult.getData();
            if ("OVERRULE".equals(data.getStatus())) {
                channelMerchantAccessQueryContext.setProcessStatus(false);
                channelMerchantAccessQueryContext.setRemark(data.getMsg());
            }
            else if ("AUDITED".equals(data.getStatus())) {
                channelMerchantAccessQueryContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.WAIT_SIGN);
                merchantAccessInfo.setSubMchId(data.getMerchantNo());
                HeliPayAccessExtentDto heliPayAccessExtentDto = new HeliPayAccessExtentDto();
                heliPayAccessExtentDto.setSysAccountNo(data.getSysAccountNo());
                merchantAccessInfo.setExtendA(JsonUtils.toJsonString(heliPayAccessExtentDto));
            }
            else {
                // 审核通过进入资料上传
                channelMerchantAccessQueryContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.CHANNEL_APPROVE);
                channelMerchantAccessQueryContext.setRemark(data.getMsg());
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            channelMerchantAccessQueryContext.setProcessStatus(false);
            channelMerchantAccessQueryContext.setRemark(e.getMessage());
        }
    }

    /**
     * 进件查询
     *
     * @param channelMerchantAccessQueryContext
     */
    public void accessAuthQueryRequest(ChannelMerchantAccessQueryContext channelMerchantAccessQueryContext) {
        CommonResult<HeliPayConfig> heliPayConfigCommonResult = heliPayMerchantParamsHandle.heliPayConfig(channelMerchantAccessQueryContext.getProviderChannelConfig(),
                channelMerchantAccessQueryContext.isTest());
        if (!heliPayConfigCommonResult.isSuccess()) {
            channelMerchantAccessQueryContext.setProcessStatus(false);
            channelMerchantAccessQueryContext.setRemark(heliPayConfigCommonResult.getMsg());
            return;
        }
        MerchantAccessInfoDO merchantAccessInfo = channelMerchantAccessQueryContext.getMerchantAccessInfo();
        HeliPayConfig heliPayConfig = heliPayConfigCommonResult.getData();
        Map<String, Object> params = new HashMap<>();
        params.put("orderNo", merchantAccessInfo.getRequestId());
        params.put("firstClassMerchantNo", heliPayConfig.getMerchantNo());
        String paramsString = JsonUtils.toJsonString(params);
        String accessUrl = heliPayMerchantParamsHandle.accessUrl(channelMerchantAccessQueryContext.isTest());
        try {
            // 审核通过查询认证状态
            CommonResult<HeliPayAccessAuthQueryRes> commonAuthResult = accessAuthQueryRequest(accessUrl, merchantAccessInfo.getSubMchId(), heliPayConfig);
            log.info("合利宝 进件认证查询 返回参数 :{}", JsonUtils.toJsonString(commonAuthResult));
            if (commonAuthResult.isSuccess()) {
                HeliPayAccessAuthQueryRes authResultData = commonAuthResult.getData();
                if ("PASS".equals(authResultData.getAuditStatus())) {
                    // 审核通过进入产品开头
                    channelMerchantAccessQueryContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.WAIT_SET);
                    channelMerchantAccessQueryContext.setAuditStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.SIGN);
                }
                else if ("WAIT_AUDIT".equals(authResultData.getAuditStatus())) {
                    channelMerchantAccessQueryContext.setAuditStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.AUDITING);
                    channelMerchantAccessQueryContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.CHANNEL_APPROVE);
                }
                else {
                    // 审核拒绝
                    StringBuilder sb = new StringBuilder();
                    if (!"PASS".equals(authResultData.getAuthResult())) {
                        sb.append("法人实名认证,失败原因:");
                        sb.append(authResultData.getAuthResultRetMsg());
                    }
                    if (!"SAME".equals(authResultData.getIdcardRecoginitionStatus())) {
                        sb.append("身份证识别认证,失败原因:");
                        sb.append(authResultData.getIdcardRecoginitionRetMsg());
                    }
                    if (!"SAME".equals(authResultData.getLicenseRecoginitionStatus())) {
                        sb.append("营业执照认证,失败原因:");
                        sb.append(authResultData.getBusinessLicenseAuthRetMsg());
                    }
                    if (!"SAME".equals(authResultData.getBusinessLicenseAuthStatus())) {
                        sb.append("商户工商信息认证,失败原因:");
                        sb.append(authResultData.getBusinessLicenseAuthRetMsg());
                    }
                    channelMerchantAccessQueryContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.APPROVE_REFUSE);
                    channelMerchantAccessQueryContext.setRemark(sb.toString());
                    channelMerchantAccessQueryContext.setProcessStatus(false);
                }
            }
            else {
                // channelMerchantAccessQueryContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.WAIT_SET);
                // channelMerchantAccessQueryContext.setAuditStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.SIGN);
                channelMerchantAccessQueryContext.setRemark(commonAuthResult.getMsg());
                channelMerchantAccessQueryContext.setProcessStatus(false);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            channelMerchantAccessQueryContext.setProcessStatus(false);
            channelMerchantAccessQueryContext.setRemark(e.getMessage());
        }
    }

    /**
     * 进件认证查询
     *
     * @param accessUrl
     * @param merchantNo
     * @param heliPayConfig
     */
    public CommonResult<HeliPayAccessAuthQueryRes> accessAuthQueryRequest(String accessUrl, String merchantNo, HeliPayConfig heliPayConfig) throws Exception {
        Map<String, Object> params = new HashMap<>();
        params.put("merchantNo", merchantNo);
        String paramsString = JsonUtils.toJsonString(params);
        return heliPayAccessRequest(accessUrl, "merchantAuthenticityAuditQuery", heliPayConfig, paramsString, HeliPayAccessAuthQueryRes.class);
    }

    /**
     * 产品开通
     *
     * @param channelMerchantAccessContext
     */
    public void accessOpenRequest(ChannelMerchantBusinessContext channelMerchantAccessContext) {
        CommonResult<HeliPayConfig> heliPayConfigCommonResult = heliPayMerchantParamsHandle.heliPayConfig(channelMerchantAccessContext.getProviderChannelConfig(),
                channelMerchantAccessContext.isTest());
        if (!heliPayConfigCommonResult.isSuccess()) {
            channelMerchantAccessContext.setProcessStatus(false);
            channelMerchantAccessContext.setRemark(heliPayConfigCommonResult.getMsg());
            return;
        }
        String accessUrl = accessUrl(channelMerchantAccessContext.isTest());
        HeliPayConfig heliPayConfig = heliPayConfigCommonResult.getData();
        MerchantAccessDto merchantAccessDto = channelMerchantAccessContext.getMerchantAccessDto();
        MerchantAccessInfoDO merchantAccessInfo = merchantAccessDto.getMerchantAccessInfo();
        List<ProviderChannelFeeConfigList> merchantFeeConfigList = channelMerchantAccessContext.getMerchantFeeConfigList();
        StringBuilder sb = new StringBuilder();

        MerchantAccessCardDO merchantAccessCard = merchantAccessDto.getMerchantAccessCard();

        for (ProviderChannelFeeConfigList merchantFeeConfig : merchantFeeConfigList) {
            if (!CommonEnum.YES_NO_TYPE.YES.getCode().equals(merchantFeeConfig.getStatus())) {
                continue;
            }
            PayWayDO payWayDO = merchantFeeConfig.getPayWayDO();
            log.info("合利宝 产品开通 支付方式 payWayCode:{}", payWayDO.getCode());

            if (Objects.equals(payWayDO.getType(), PayEnums.PAY_TYPE.FUNCTION.getCode())) {
                Map<String, Object> params = heliPayMerchantParamsHandle.merchantOpenSettleProductParams(merchantAccessCard, merchantFeeConfig);
                params.put("firstClassMerchantNo", heliPayConfig.getMerchantNo());
                params.put("merchantNo", merchantAccessInfo.getSubMchId());
                try {
                    CommonResult<Map> commonResult = heliPayAccessRequest(accessUrl, "openProduct", heliPayConfig, JsonUtils.toJsonString(params), Map.class);
                    log.info("合利宝 结算产品开通 返回参数 :{}", JsonUtils.toJsonString(commonResult));
                    if (!commonResult.isSuccess()) {
                        sb.append("支付方式:" + payWayDO.getName());
                        sb.append(";支付编码:" + payWayDO.getCode());
                        sb.append(";合利宝支付类型:" + params.get("payType"));
                        sb.append(";合利宝客户端类型:" + params.get("appPayType"));
                        sb.append(";产品开通失败,失败原因:");
                        sb.append(commonResult.getMsg());
                        sb.append("\n");
                    }
                }
                catch (Exception e) {
                    sb.append(e.getMessage());
                    sb.append("\n");
                }
            }
            else {
                PayEnums.SCENE_PAY_TYPE scenePayType = PayEnums.SCENE_PAY_TYPE.fromByType(payWayDO.getSubType());
                if (scenePayType == null) {
                    continue;
                }
                Map<String, Object> params = heliPayMerchantParamsHandle.merchantOpenAppPayProductParams(merchantFeeConfig);
                if (params == null) {
                    continue;
                }
                params.put("firstClassMerchantNo", heliPayConfig.getMerchantNo());
                params.put("merchantNo", merchantAccessInfo.getSubMchId());
                if (StringUtils.hasText(heliPayConfig.getFeePurpose())) {
                    params.put("feePurpose", heliPayConfig.getFeePurpose());
                }
                else {
                    params.put("feePurpose", "DEFAULT");
                }
                try {
                    CommonResult<Map> commonResult = heliPayAccessRequest(accessUrl, "openProduct", heliPayConfig, JsonUtils.toJsonString(params), Map.class);
                    log.info("合利宝 扫码产品开通 返回参数 :{}", JsonUtils.toJsonString(commonResult));
                    if (!commonResult.isSuccess()) {
                        sb.append("支付方式:" + payWayDO.getName());
                        sb.append(";支付编码:" + payWayDO.getCode());
                        sb.append(";合利宝支付类型:" + params.get("payType"));
                        sb.append(";合利宝客户端类型:" + params.get("appPayType"));
                        sb.append(";产品开通失败,失败原因:");
                        sb.append(commonResult.getMsg());
                        sb.append("\n");
                    }
                }
                catch (Exception e) {
                    sb.append(e.getMessage());
                    sb.append("\n");
                }
            }
        }
        String remark = sb.toString();
        if (StringUtils.hasText(remark)) {
            channelMerchantAccessContext.setRemark(remark);
            // channelMerchantAccessContext.setProcessStatus(false);
        }
        channelMerchantAccessContext.setAuditStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.SUBMERINFO);
    }

    /**
     * 
     * @param channelMerchantAccessContext
     */
    public void accessSignRequest(ChannelMerchantAccessSignContext channelMerchantAccessContext) {
        CommonResult<HeliPayConfig> heliPayConfigCommonResult = heliPayMerchantParamsHandle.heliPayConfig(channelMerchantAccessContext.getProviderChannelConfig(),
                channelMerchantAccessContext.isTest());
        if (!heliPayConfigCommonResult.isSuccess()) {
            channelMerchantAccessContext.setProcessStatus(false);
            channelMerchantAccessContext.setRemark(heliPayConfigCommonResult.getMsg());
            return;
        }
        String accessUrl = accessUrl(channelMerchantAccessContext.isTest());
        HeliPayConfig heliPayConfig = heliPayConfigCommonResult.getData();
        MerchantAccessInfoDO merchantAccessInfo = channelMerchantAccessContext.getMerchantAccessInfoDO();
        Map<String, Object> params = new HashMap<>();
        params.put("merchantNo", heliPayConfig.getMerchantNo());
        params.put("emerchantNo", merchantAccessInfo.getSubMchId());
        try {
            CommonResult<Map> commonResult = heliPayAccessRequest(accessUrl, "getSignContractUrl", heliPayConfig, JsonUtils.toJsonString(params), Map.class);
            log.info("合利宝 获取电子合同签约 返回参数 :{}", JsonUtils.toJsonString(commonResult));
            if (commonResult.isSuccess()) {
                Map<String, String> data = commonResult.getData();
                String signContractUrl = data.get("signContractUrl");
                MerchantAccessSignLink merchantAccessSignLink = new MerchantAccessSignLink();
                merchantAccessSignLink.setLink(signContractUrl);
                merchantAccessSignLink.setName("签章合同");
                // merchantAccessSignLink.setType();
                channelMerchantAccessContext.setSignLinks(new ArrayList<>() {

                    {
                        add(merchantAccessSignLink);
                    }
                });
                channelMerchantAccessContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.WAIT_SIGNING);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            // channelMerchantAccessQueryContext.setProcessStatus(false);
            // channelMerchantAccessQueryContext.setRemark(e.getMessage());
        }
    }

    public void accessSignQueryRequest(ChannelMerchantAccessSignContext channelMerchantBusinessContext) {
        CommonResult<HeliPayConfig> heliPayConfigCommonResult = heliPayMerchantParamsHandle.heliPayConfig(channelMerchantBusinessContext.getProviderChannelConfig(),
                channelMerchantBusinessContext.isTest());
        if (!heliPayConfigCommonResult.isSuccess()) {
            channelMerchantBusinessContext.setProcessStatus(false);
            channelMerchantBusinessContext.setRemark(heliPayConfigCommonResult.getMsg());
            return;
        }
        String accessUrl = accessUrl(channelMerchantBusinessContext.isTest());
        HeliPayConfig heliPayConfig = heliPayConfigCommonResult.getData();
        MerchantAccessInfoDO merchantAccessInfo = channelMerchantBusinessContext.getMerchantAccessInfoDO();
        Map<String, Object> params = new HashMap<>();
        params.put("merchantNo", merchantAccessInfo.getSubMchId());
        try {
            CommonResult<Map> commonResult = heliPayAccessRequest(accessUrl, "contractQuery", heliPayConfig, JsonUtils.toJsonString(params), Map.class);
            log.info("合利宝 获取电子合同签约状态 返回参数 :{}", JsonUtils.toJsonString(commonResult));
            if (commonResult.isSuccess()) {
                Map<String, String> data = commonResult.getData();
                String signStatus = data.get("signStatus");
                if ("1".equals(signStatus)) {
                    channelMerchantBusinessContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.WAIT_SET);
                    channelMerchantBusinessContext.setAuditStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.OPEN_PRODUCT);
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            // channelMerchantAccessQueryContext.setProcessStatus(false);
            // channelMerchantAccessQueryContext.setRemark(e.getMessage());
        }
    }
}
